package network;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Collection;
import java.util.Iterator;
import java.util.Vector;

public class MultiChatServerThread extends Thread {
	
	private MultiChatServer server;
	private Socket socket;
	ObjectOutputStream send;
	ObjectInputStream receive;

	public MultiChatServerThread(MultiChatServer multiChatServer, Socket client) {
		this.server = multiChatServer;
		this.socket = client;
		this.start();
	}

	@Override
	public void run() {
		try {
			send = new ObjectOutputStream(socket.getOutputStream());
			receive = new ObjectInputStream(socket.getInputStream());
			
			while (true) {
								
				Object o = receive.readObject();
				if (o instanceof SocketData && SocketData.serialVersionUID == 100000) {
				
				InetAddress di = server.client.getInetAddress();//상대 아이피를 구함
				SocketData sdIn = (SocketData) o; //받아온 걸 저장하는 곳을 가르키는 sd

				if(sdIn.getCommand().equals("login")){
					server.clients.put(sdIn.getUser(),this);
					Collection c = server.clients.keySet();
					Object[] temp = c.toArray();
					server.list.setListData(temp);
					
					sdIn.setCommand("userlist");
					sendUserList(sdIn, c);
					server.dataSet(String.valueOf(di));//상대 아이피 주소 출력
					server.dataSet(sdIn);
				}
				else if(sdIn.getCommand().equals("logout")){
					server.dataSet(sdIn);
					server.clients.remove(sdIn.getUser());
					Collection<String> c= server.clients.keySet();
					Object temp[] = c.toArray();
					server.list.setListData(temp);
				}
				else	server.dataSet(sdIn);
				
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void sendMsg(SocketData sd){ //전체 공지를 위한 것
		try{
			Collection<String> c = server.clients.keySet();
			Iterator<String> it = c.iterator();
			while(it.hasNext()){
				MultiChatServerThread t = (MultiChatServerThread) server.clients.get(it.next()); // 이걸 통해서 데이터 보내기 가능*****************
				t.send.writeObject(sd);
			}
			
		}catch(Exception ex){
			ex.printStackTrace();
		}
		
	}
	// 클라이언트가 접속되면 서버가 저장하고 있는 모든 유저 목록을 object에 담아 모든 유저에게 전송함.
	public void sendUserList(SocketData sd, Collection<String> c) {
		Iterator<String> it = c.iterator();
		Vector v = new Vector<>();

		while (it.hasNext()) {
			v.add(it.next());
		}

		sd.setObj(v);
		sendMsg(sd); // userlist인지 받는 사람은 어떻게 앎?
	}

}
